/* 
 * @Author: 21克的爱情
 * @Date: 2020-10-04 13:09:52
 * @Email: raohong07@163.com
 * @LastEditors: 21克的爱情
 * @LastEditTime: 2020-10-05 15:55:42
 * @Description: 
 */
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class SQliteMessage{
  static const String DataBaseName = "ki5k_data_base.db";
  static const String tableShelf = "bookShelf";
  static const String tablePlayData = "play_data";
  static const String tableSearch = "ki5k_search";

  final String dropTableShelf = "DROP TABLE IF EXISTS $tableShelf";
  final String createTableShelf = "CREATE TABLE $tableShelf (id INTEGER PRIMARY KEY AUTOINCREMENT, bookId TEXT"
      ",title TEXT,readers REAL,briefIntro TEXT,charactersCount INTEGER"
      ",chaptersCount INTEGER,cover TEXT,serialState INTEGER"
      ",majorCateId TEXT,majorCateName TEXT"
      ",minorCateId TEXT,minorCateName TEXT"
      ",ratio REAL,author TEXT,lastReadTime INTEGER)";


  final String dropTableSearch = "DROP TABLE IF EXISTS $tableSearch";
  final String createTableSearch = "CREATE TABLE $tableSearch (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, pic TEXT, url TEXT, counts INTEGER, updateTime INTEGER, createTime INTEGER)";

  final String dropTablePlayData = "DROP TABLE IF EXISTS $tablePlayData";
  final String createPlayData = "CREATE TABLE $tablePlayData (id INTEGER PRIMARY KEY AUTOINCREMENT, vod_id TEXT, vod_pic TEXT, vod_name TEXT, vod_play_url TEXT, updateTime INTEGER, createTime INTEGER)";

  Database _db;

  Future<Database> get db async{
    if(_db == null){
      _db = await _initDb();
    }
    return _db;
  }

  _initDb() async{
    String basePath = await getDatabasesPath();
    String path = join(basePath, DataBaseName);
    Database db = await openDatabase(path,version: 2,onCreate: _onCreate,onUpgrade: _onUpgrade);
    return db;
  }

  Future close() async {
    var result = _db.close();
    _db = null;
    return result;
  }

  void _onCreate(Database db, int newVersion) async{
    print("_onCreate newVersion:$newVersion");
    var batch = db.batch();
    batch.execute(dropTableShelf);
    batch.execute(createTableShelf);

    batch.execute(dropTablePlayData);
    batch.execute(createPlayData);

    batch.execute(dropTableSearch);
    batch.execute(createTableSearch);
    await batch.commit();
  }

  void _onUpgrade(Database db, int oldVersion,int newVersion)async{
    print("_onUpgrade oldVersion:$oldVersion");
    print("_onUpgrade newVersion:$newVersion");

    var batch = db.batch();
    if(oldVersion == 1){
      batch.execute(dropTablePlayData);
      batch.execute(createPlayData);
    }

    await batch.commit();

  }
}